// 二次封装axios
import axios from "axios";

// 进度条
import nProgress from "nprogress";
import "nprogress/nprogress.css"

// 实例化
const install = axios.create({
    baseURL: "http://localhost:3002",
    timeout: 5000
})

// 请求拦截
install.interceptors.request.use(
    (config) => {
        // 开始进度
        nProgress.start();
        // 请求头携带token
        const token = localStorage.getItem("token");
        if (token) {
            config.headers["Authorization"] = "Bearer " + token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error)
    }
)


// 响应拦截
install.interceptors.response.use(
    (response) => {
        // 结束进度
        nProgress.done()
        return response;
    },
    (error) => {
        // 请求超时处理
        if (error.message.includes("timeout")) {
            alert("请求超时!")
            return;
        }
        // 错误状态码
        const code = error.response.status;
        switch (code) {
            case 400:
                console.log("请求错误");
                break;
            case 401:
                console.log("未授权");
                break;
            case 403:
                console.log("禁止访问");
                break;
            case 404:
                console.log("页面消失");
                break;
            case 500:
                console.log("服务器内部错误");
                break;
            case 502:
                console.log("网关错误");
                break;
        }

        return Promise.reject(error)
    }
)

// 导出
export default install